﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Solidi
{
    sealed class CircularDependency
    {
        private IDependencyKey _key;
        private IList<IDependency> _dependencies;
        private int _index;

        public CircularDependency(IDependencyKey key)
        {
            _key = key;
        }

        public bool IsCircular(IDependencyKey key)
        {
            return DependencyKeyEqualityComparer.Default.Equals(_key, key);
        }

        public bool TryAcquirePrevious(object graphId, IDependencyContainer container, out object instance)
        {
            if (_dependencies == null)
            {
                _dependencies = container.Registry.Find(_key, null).ToArray();

                _index = _dependencies.Count - 1;
            }

            if (--_index < 0)
            {
                instance = null;

                return false;
            }

            return container.Lifetime.TryAcquire(graphId, container, _dependencies[_index], out instance);
        }
    }
}
